#include <iostream>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <unordered_set>
#include <unordered_map>
using namespace std;
#define NUM 1024
int main(int argc, char *argv[])
{
    unordered_map<uint16_t,sockaddr_in> usdate;
    // 创建套接字
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        cout << "sock enrro" << endl;
        exit(1);
    }
    // 绑定
    sockaddr_in se;
    memset(&se, 0, sizeof(se));
    se.sin_family = AF_INET;
    se.sin_port = htons(atoi(argv[2]));
    se.sin_addr.s_addr = inet_addr(argv[1]);
    int ret = bind(sock, (sockaddr *)&se, sizeof(se));
    if (ret < 0)
    {
        cout << "bind enrro" << endl;
        exit(2);
    }
    // 服务端    1.0版本
    // 可以开始读取
    // sockaddr_in reader;
    // socklen_t size = sizeof(reader);
    // char buffer[NUM];
    // while (true)
    // {
    //     ssize_t r = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&reader, &size);
    //     buffer[r] = '\0';
    //     if (r > 0)
    //     {
    //         cout << buffer << endl;
    //     }
    //     else
    //         break;
    //     sendto(sock, buffer, sizeof(buffer), 0, (sockaddr *)&reader, size);
    //     memset(buffer, 0, sizeof(buffer));
    // }
    // close(sock);
    // 服务器 2.0版本 实现群聊
    char buffer[NUM];
    memset(buffer, 0, NUM);
    sockaddr_in reader;
    socklen_t size = sizeof(reader);
    while (true)
    {
        ssize_t s = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&reader, &size);
        usdate.insert(make_pair(reader.sin_port, reader));
        cout << "插入成功" << endl;
        cout << ntohs(reader.sin_port) <<" "<< inet_ntoa(reader.sin_addr)<< '#' << " "
             << ":" << buffer << endl;
        if (s > 0)
        {
            for (const auto &e : usdate)
                sendto(sock, buffer, sizeof(buffer), 0, (sockaddr *)&(e.second), sizeof(e.second));
            memset(buffer, 0, NUM);
        }
        else
            break;
    }
    close(sock);
    return 0;
}
